import Vue from 'vue';
import VueRouter from 'vue-router';
import Login from '../views/Login.vue';
import Home from '../views/Home.vue';
import Welcome from '../views/Welcome.vue';
import Users from '../views/user/Users.vue';
import Register from '../views/Register.vue';
import apiData from '../views/data/apiData.vue';

Vue.use(VueRouter);

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/apiData', component: apiData },
    ],
  },
];

const router = new VueRouter({
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.path === '/register' || to.path === '/login') return next();
  if (
    !sessionStorage.getItem('userName') ||
    new Date().getTime() - sessionStorage.getItem('loginTime') > 30 * 60 * 1000
  )
    return next('/login');
  next();
});

export default router;
